package cn.felord.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * webSocket 配置类
 * {@link WebSocketConfigurer} 主要用来配置 webSocket 请求处理的回调方法 需要与 {@link EnableWebSocket} 配合使用
 * {@link WebSocketConfigurer#registerWebSocketHandlers(WebSocketHandlerRegistry)}  回调方法注册
 *
 * @author Dax
 * @since 11 :43  2018/7/6
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(defaultWsHandler(), "/ws")
                .setAllowedOrigins("*")
                .addInterceptors(defaultHandshakeInterceptor())
                .withSockJS();
    }

    /**
     * Default ws handler web socket handler.
     *
     * @return the web socket handler
     */
    @Bean
    public WebSocketHandlerProxy defaultWsHandler() {
        return new DefaultWebSocketHandler();
    }

    /**
     * Default handshake interceptor handshake interceptor.
     *
     * @return the handshake interceptor
     */
    @Bean
    public HandshakeInterceptor defaultHandshakeInterceptor() {
        return new DefaultWebSocketInterceptor();
    }
}
